package
{
  import flash.display.Sprite;
  import flash.filters.DropShadowFilter;
  import flash.events.MouseEvent;

  public class PieChart extends Sprite
  {
    private var radius:Number;
    private var data:Array;
    private var arcs:Array = [];
    private var tooltip:Tooltip;
    private var colors:Array = [ 0xffaaaa, 0xaaffaa, 0xaaaaff, 0xffaaff, 0xffffaa, 0xaaffff ];

    public function PieChart(x:Number, y:Number, radius:Number)
    {
      this.x = x;
      this.y = y;
      this.radius = radius;
      this.data = [];
    }

    public function clearData():void {
      data = [];
    }
   
    public function addData(value:Number, legend:String):void {
      data.push([ value, legend || value ]);
    }
   
    public function paint():void {
      var circle:Sprite = new Sprite();
      circle.graphics.clear();
      circle.graphics.beginFill(0xffffff);
      circle.graphics.drawCircle(0, 0, radius)
      circle.graphics.endFill();
      var dropShadow:DropShadowFilter = new DropShadowFilter();
      dropShadow.distance = radius * .05
      circle.filters = [ dropShadow ];
      addChild(circle);

      var sum:Number = 0;
      for (var i:int=0; i<data.length; i++) sum += data[i][0];
      var startAngle:Number = -90;
      data.forEach(function(pdata:Object, i:int, data:Array):void {
        var angle:Number = pdata[0] * 360/sum;
        var arc:Arc = new Arc(colors[i % colors.length], 0, 0, radius, angle, startAngle);
        arcs.push(arc);
        arc.addEventListener(MouseEvent.MOUSE_OVER, function(e:*):void {
          tooltip.x = arc.centerX;
          tooltip.y = arc.centerY;
          tooltip.text = pdata[1]+'\n'+pdata[0];
          tooltip.visible = true;
          arc.alpha = .5;
        });
        arc.addEventListener(MouseEvent.MOUSE_OUT, function(e:*):void {
          tooltip.visible = false;
          arc.alpha = 1;
        });
        addChild(arc);
        startAngle += angle;
      })

      tooltip = new Tooltip(0xaaaaaa, 0xffffff, .8, radius*.75, radius*.5);
      tooltip.visible = false;
      addChild(tooltip);
    }
    
    
  }
}

 
